//
//  GW_Tool.m
//  IMHuanXin
//
//  Created by 小獾科技 on 2017/7/27.
//  Copyright © 2017年 小獾科技. All rights reserved.
//

#import "GW_Tool.h"
#import <AudioToolbox/AudioToolbox.h>//手机振动
#import "OpenUDID.h"
#import <AdSupport/AdSupport.h>//获取IDFA用的头文件
@implementation GW_Tool

static GW_Tool *tool = nil;
+ (GW_Tool *)sharedInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tool = [[self alloc] init];
    });
    return tool;
}

+ (void)configAppStyle {
    
//    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
//    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];

    
//    [[UINavigationBar appearance] setTintColor:ColorWhite];// 导航条上面icon颜色
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSFontAttributeName:PFRFONT(18),
                                                           NSForegroundColorAttributeName:ColorFrom16(0x202020)}];// 导航条上面字体颜色
//    [[UINavigationBar appearance] setTranslucent:NO];//设置导航栏半透明，默认是YES
    
//    [[UITabBar appearance] setBackgroundImage:[IMAGE(@"nav_bg") stretchableImageWithLeftCapWidth:10 topCapHeight:10]];
//    [[UITabBar appearance] setShadowImage:[IMAGE(@"tabbar_bg_line") stretchableImageWithLeftCapWidth:10 topCapHeight:0]];
    [[UITabBar appearance] setBackgroundColor:ColorFrom16(0xffffff)];
    
    [[UITabBarItem appearance] setTitleTextAttributes:@{NSFontAttributeName:PFRFONT(12),
                                                        NSForegroundColorAttributeName:COLOR_FOR_BAR_TEXT_NOR} forState:UIControlStateNormal];//设置tabbar字体颜色
    [[UITabBarItem appearance] setTitleTextAttributes:@{NSFontAttributeName:PFRFONT(12),
                                                        NSForegroundColorAttributeName:COLOR_FOR_BAR_TEXT_SEL} forState:UIControlStateSelected];//设置tabbar点击高亮字体颜色
    
    [[UITabBar appearance] setTranslucent:NO];
}

// 手机震动
+ (void)deviceShortShake {
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}

/** className model的类名  id类型model接收*/
+ (id)getObjFromDictionary:(NSDictionary *)dict byClassName:(NSString *)className{
    
    Class aClass = NSClassFromString(className);
    id obj = [[aClass alloc]init];
    if ((!dict) || (![dict isKindOfClass:[NSDictionary class]])) {
        return obj;
    }
    for (NSString *key in [dict allKeys]) {
        NSString *firstChar = [[key substringToIndex:1]uppercaseString];
        NSRange range = NSMakeRange(0, 1);
        NSString *selTempStr = [key stringByReplacingCharactersInRange:range withString:firstChar];
        
        SEL selName =NSSelectorFromString([NSString stringWithFormat:@"set%@:",selTempStr]);
        if ([aClass instancesRespondToSelector:selName]) {
            
            if([[dict objectForKey:key] isKindOfClass:[NSArray class]]||[[dict objectForKey:key] isKindOfClass:[NSDictionary class]]){
                [obj setValue:[dict objectForKey:key] forKey:key];
            }else if ([dict objectForKey:key]){
                NSString *valueStr =  [dict objectForKey:key]?[NSString stringWithFormat:@"%@",[dict objectForKey:key]]:@"";
                [obj setValue:valueStr forKey:key];
            }
        }
    }
    
    return obj;
}

+ (NSString *)dictionaryToURLParamsString:(NSDictionary *)params {
    
    NSMutableString *multStr=[NSMutableString string];
    //按字母顺序排序
    NSArray *keys = [params allKeys];
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    //拼接字符串
    for (NSString *categoryId in sortedArray) {
        if ( [multStr length] > 0) {
            [multStr appendString:@"&"];
        }
        [multStr appendFormat:@"%@=%@", categoryId, [params objectForKey:categoryId]];
        
    }
    
    return [NSString stringWithString:multStr];
}

+ (NSString *)formatString:(NSString *)str {
    
    if (str == nil) {
        return @"";
    }
    
    if ([str isKindOfClass:[NSNumber class]]) {
        NSNumber *numStr = (NSNumber *)str;
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        str = [numberFormatter stringFromNumber:numStr];
    }
    
    NSSet *nullSet = [NSSet setWithObjects:@"NULL",@"Null",@"null",@"(NULL)",@"(Null)",@"(null)",@"<NULL>",@"<Null>",@"<null>", nil];
    if ([nullSet containsObject:str]) {
        return @"";
    }
    
    return [NSString stringWithFormat:@"%@",str];
}

+ (BOOL)isEmptyString:(NSString *)str {
    
    if ([@"" isEqualToString:[self formatString:str]]) {
        return YES;
    }
    return NO;
}

// 字符串转16进制
+ (int)stringToHexadecimal:(NSString *)aStr {
    
    int i;
    sscanf([aStr cStringUsingEncoding:NSASCIIStringEncoding], "%x", &i);
    return i;
}

+ (void)getIdentifying:(UIButton *)sender
{
    //设置倒计时时间
    //通过检验发现，方法调用后，timeout会先自动-1，所以如果从15秒开始倒计时timeout应该写16
    //__block 如果修饰指针时，指针相当于弱引用，指针对指向的对象不产生引用计数的影响
    __block int timeout = 61;
    
    //获取全局队列
    dispatch_queue_t global = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    //创建一个定时器，并将定时器的任务交给全局队列执行(并行，不会造成主线程阻塞)
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, global);
    
    // 设置触发的间隔时间
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    //1.0 * NSEC_PER_SEC  代表设置定时器触发的时间间隔为1s
    //0 * NSEC_PER_SEC    代表时间允许的误差是 0s
    
    //block内部 如果对当前对象的强引用属性修改 应该使用__weak typeof(self)weakSelf 修饰  避免循环调用
    //设置定时器的触发事件
    dispatch_source_set_event_handler(timer, ^{
        
        //倒计时  刷新button上的title ，当倒计时时间为0时，结束倒计时
        
        //1. 每调用一次 时间-1s
        timeout --;
        
        //2.对timeout进行判断时间是停止倒计时，还是修改button的title
        if (timeout <= 0) {
            
            //停止倒计时，button打开交互，背景颜色还原，title还原
            
            //关闭定时器
            dispatch_source_cancel(timer);
            
            //MRC下需要释放，这里不需要
            // dispatch_realse(timer);
            
            //button上的相关设置
            //注意: button是属于UI，在iOS中多线程处理时，UI控件的操作必须是交给主线程(主队列)
            //在主线程中对button进行修改操作
            dispatch_async(dispatch_get_main_queue(), ^{
                //                weakSelf.getIdentifyingBtn.userInteractionEnabled = YES;//开启交互性
                //                weakSelf.getIdentifyingBtn.backgroundColor = ColorFrom16(0xf9bc4f);
                //                [weakSelf.getIdentifyingBtn setTitle:@"点击获取" forState:UIControlStateNormal];
                
                sender.userInteractionEnabled = YES;//开启交互性
                sender.backgroundColor = ColorFrom16(0xf9bc4f);
                [sender setTitle:@"点击获取" forState:UIControlStateNormal];
            });
        }else {
            
            //处于正在倒计时，在主线程中刷新button上的title，时间-1秒
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString * title = [NSString stringWithFormat:@"%ds",timeout];
                //                [weakSelf.getIdentifyingBtn setTitle:title forState:UIControlStateNormal];
                //                weakSelf.getIdentifyingBtn.backgroundColor = ColorFrom16(0xe2e2e2);
                //                weakSelf.getIdentifyingBtn.userInteractionEnabled = NO;//关闭交互性
                
                [sender setTitle:title forState:UIControlStateNormal];
                sender.backgroundColor = ColorFrom16(0xe2e2e2);
                sender.userInteractionEnabled = NO;//关闭交互性
            });
        }
    });
    
    dispatch_resume(timer);
}

// 计算UILabel显示区域
+ (CGSize)sizeOfLabelWithString:(NSString *)string font:(UIFont *)font width:(CGFloat)width {
    
    CGSize size = [string boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil].size;
    return size;
}

// 获取uuid  得配合 OPenUUID三方库
+ (NSString *)getDeviceIDFA
{
    NSString *idfaString = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    if (idfaString.length == 0) {
        idfaString = [OpenUDID value];
    }
    
    
    // 用户名密码备用
    //    KeychainItemWrapper *keychainAccount = [[KeychainItemWrapper alloc] initWithIdentifier:@"com.answern.answern.account" accessGroup:nil];
    //    [keychainAccount setObject:@"little Pig" forKey:(id)kSecAttrAccount];//账户名//  //
    //    [keychainAccount setObject:@"123456" forKey:(id)kSecValueData];//账户密码
    
    return idfaString;
}

+ (UIImage *)createGradualImage:(CGSize)size startColor:(UIColor *)startColor endColor:(UIColor *)endColor startLoction:(NSInteger)idx {
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
    
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = view.bounds;
    //设置渐变区域的起始和终止位置（范围为0-1），即渐变路径
    switch (idx) {
        case 0:// 从左到右
        {
            gradientLayer.startPoint = CGPointMake(0.0, 0.0);
            gradientLayer.endPoint = CGPointMake(1.0, 0.0);
        }
            break;
        case 1:// 从下到上
        {
            gradientLayer.startPoint = CGPointMake(0, 1.0);
            gradientLayer.endPoint = CGPointMake(0.0, 0.0);
        }
            break;
        default:
        {
            gradientLayer.startPoint = CGPointMake(0.0, 0.0);
            gradientLayer.endPoint = CGPointMake(1.0, 0.0);
        }
            break;
    }
    gradientLayer.colors = @[(__bridge id)startColor.CGColor, (__bridge id)endColor.CGColor];
    [view.layer addSublayer:gradientLayer];
    
    UIGraphicsBeginImageContext(size);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

+ (void)saveLoginInfoWithDict:(NSDictionary *)dict
{
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kUDIsLogin];
    [[NSUserDefaults standardUserDefaults] setObject:STRING([dict objectForKey:@"id"]) forKey:kUDUserId];
    [[NSUserDefaults standardUserDefaults] setObject:STRING([dict objectForKey:@"openid"]) forKey:kUDUserOpenId];
    [[NSUserDefaults standardUserDefaults] setObject:STRING([dict objectForKey:@"unionid"]) forKey:kUDUserUnionId];
    [[NSUserDefaults standardUserDefaults] setObject:STRING([dict objectForKey:@"avatar"]) forKey:kUDUserHead];
    [[NSUserDefaults standardUserDefaults] setObject:STRING([dict objectForKey:@"baby_name"]) forKey:kUDBabyName];
    [[NSUserDefaults standardUserDefaults] setObject:STRING([dict objectForKey:@"access_token"]) forKey:kUDUserToken];
    [[NSUserDefaults standardUserDefaults] setObject:STRING(dict[@"baby_birthday"]) forKey:kUDBabyBirthday];
    [[NSUserDefaults standardUserDefaults] setObject:STRING(dict[@"baby_sex"]) forKey:kUDBabySex];
    [[NSUserDefaults standardUserDefaults] setObject:STRING(dict[@"type"]) forKey:KUDUserLoginType];
    [[NSUserDefaults standardUserDefaults] setObject:STRING(dict[@"token"]) forKey:kUDtoken];
    [[NSUserDefaults standardUserDefaults] setObject:STRING(dict[@"name"]) forKey:kUDUName];//用户名
    [[NSUserDefaults standardUserDefaults] setObject:STRING(dict[@"phone"]) forKey:kUDUserTel];
    [[NSUserDefaults standardUserDefaults] setObject:STRING(dict[@"balance"]) forKey:kUDBalance];
    [[NSUserDefaults standardUserDefaults] setObject:STRING(dict[@"vip"]) forKey:kUDVip];
    [[NSUserDefaults standardUserDefaults] setObject:STRING(dict[@"age"]) forKey:kUDAge];


}

+ (void)clearLoginInfo{
    
    // 移除友盟推送别名，放在清除用户信息之前
//    [GlobalTool removeUMessageAlias];
    
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:kUDIsLogin];
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:kUDUserId];
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:kUDUserOpenId];
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:kUDUserUnionId];
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:kUDUserTel];
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:kUDUserHead];
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:kUDUserToken];
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:kUDUName];//用户名
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:kUDtoken];//
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:kUDBabySex];//
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:kUDBabyBirthday];//
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:kUDBabyName];//宝宝姓名
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:KUDUserLoginType];//用户名
    [[NSUserDefaults standardUserDefaults] setObject:@""forKey:kUDBalance];
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:kUDVip];

    [[NSUserDefaults standardUserDefaults] synchronize];

    
    // 清除web缓存
//    [GlobalTool clearWebCache];
    
    // 清除所有缓存
//    [[PINCache sharedCache] removeAllObjects];
    
}

//设置字体  中间划横线
+ (NSMutableAttributedString *)setCutLine:(NSString *)string
{
    NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleThick]};
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:string attributes:attribtDic];
    return attributeStr;
}

+ (NSMutableAttributedString *)setTextColor:(UIColor *)color rangeOfString:(NSString *)rangeString string:(NSString *)string textFont:(CGFloat)font
{
    NSMutableAttributedString *aString = [[NSMutableAttributedString alloc] initWithString:string];
    NSRange range = [[aString string]rangeOfString:rangeString];
    [aString addAttribute:NSForegroundColorAttributeName value:color range:range];
    [aString addAttribute:NSFontAttributeName value:PFRFONT(font) range:range];
    return aString;
}

+ (NSMutableAttributedString *)setTextSpace:(NSString *)string textSpaceSize:(CGFloat)size
{
    NSDictionary *dic = @{NSKernAttributeName:@(size)
                          };
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string attributes:dic];
    return attributedString;
}

+ (NSString *)getWebConfigCookieScript {
    
    NSString *cookieString0 = [NSString stringWithFormat:@"document.cookie='PAILE_UUID=%@;path=/;domain=%@';",@"",@".paile.yanfaguanjia.cn"];
    NSString *cookieString1 = @"";
    
    if (IS_LOGIN) {
        
        cookieString1 = [NSString stringWithFormat:@"document.cookie='PAILE_UUID=%@;path=/;domain=%@';",TOKEN,@".paile.yanfaguanjia.cn"];
    }
    
    NSString *cookieScript = [NSString stringWithFormat:@"%@%@",cookieString0,cookieString1];
    
    return cookieScript;
}

// Cookie
+ (NSString *)getHttpHeaderCookieString {
    
    NSString *cookieString0 = [NSString stringWithFormat:@"pailexiong_from=%@;",@""];
    NSString *cookieString1 = @"PAILE_UUID=;";
    
    if (IS_LOGIN) {
        
        cookieString1 = [NSString stringWithFormat:@"PAILE_UUID=%@;",TOKEN];
    }
    
    NSString *cookieString = [NSString stringWithFormat:@"%@%@",cookieString0,cookieString1];
    return cookieString;
}

+ (void)versionCheck
{
    [NetWork sendGetRequestURL:[NSString stringWithFormat:@"%@/common/version", GW_Domain] parameters:nil completionBlockWithSuccess:^(NSDictionary *resultDict) {
        NSLog(@" 检查版本更新  %@", resultDict);
        NSDictionary *dict = resultDict[@"data"];
        if(![APP_VERSION isEqualToString:dict[@"versionName"]])
        {
            AlertViewManager *alert = [[AlertViewManager alloc] initWithTitle:@"发现新版本" message:@"检测到新版本是否更新?" cancelButtonTitle:@"取消" confirmButtonTitle:@"确定" delegate:[UIApplication sharedApplication].keyWindow block:^(NSInteger idx) {
                if(idx == 1)
                {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:dict[@"update_link"]]];
                    //https://itunes.apple.com/gb/app/pai-le-xiong/id1294951586?mt=8
                    NSLog(@"去更新");
                }
            }];
            [alert show];
        }
    } andFailure:^(NSError *error, NSString *errorMsg) {
        NSLog(@"%@", error);
    }];
}

+ (void)telephoneCallup:(NSString *)telephoneNumber
{
    AlertViewManager *alertView = [[AlertViewManager alloc] initWithTitle:[NSString stringWithFormat:@"拨打%@",telephoneNumber] message:@"派乐熊将为您提供更安心的服务" cancelButtonTitle:@"我再逛逛" confirmButtonTitle:@"联系客服" delegate:[UIApplication sharedApplication].keyWindow block:^(NSInteger idx) {
        
        if (idx == 1) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",telephoneNumber]]];
        }
    }];
    [alertView show];
}


@end
